package alice.exercise.leetcode.simple;

import java.util.LinkedList;

/**
 * 706. 设计哈希映射
 *
 * @author Alice
 * @since 2023-02-21 星期二 18:11
 */
public class MyHashMap {
  private static final int BASE = 997;
  private final LinkedList<MyNode>[] values;

  public MyHashMap() {
    values = new LinkedList[BASE];
  }

  public void put(int key, int value) {
    int location = key % BASE;
    if (values[location] == null) {
      values[location] = new LinkedList<MyNode>();
      values[location].add(new MyNode(key, value));
      return;
    }
    for (MyNode n : values[location]) {
      if (n.key == key) {
        n.val = value;
        return;
      }
    }
    values[location].addLast(new MyNode(key, value));
  }

  public int get(int key) {
    int location = key % BASE;
    if (values[location] == null) {
      return -1;
    }
    for (MyNode n : values[location]) {
      if (n.key == key) {
        return n.val;
      }
    }
    return -1;
  }

  public void remove(int key) {
    int location = key % BASE;
    if (values[location] == null) {
      return;
    }
    for (MyNode n : values[location]) {
      if (n.key == key) {
        values[location].remove(n);
        return;
      }
    }
  }

  static class MyNode {
    int key;
    int val;

    public MyNode(int key, int value) {
      this.key = key;
      this.val = value;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      MyNode myNode = (MyNode) o;

      return key == myNode.key;
    }

    @Override
    public int hashCode() {
      return key;
    }
  }
}
